import { message } from "antd";
import html2canvas from "html2canvas";

function transformLink(url: string) {
  if (url?.includes("https://etonkids-file.oss-cn-beijing.aliyuncs.com")) {
    return `https://assesstest.kafamily.cn/img?l=${url}`;
  }
  return url;
}
/**
 * 生成活动表格并返回图片
 * @param {Array} data - 活动数据数组
 * @returns {Promise<HTMLImageElement>} - 返回包含表格的图片元素
 */
export default async function generateActivityTableImage(data) {
  // 1. 预处理数据：按日期分组并排序
  const groupedData = {};
  data.forEach((item) => {
    const date = item.timeAtStartStr.split(" ")[0]; // 提取日期部分
    if (!groupedData[date]) {
      groupedData[date] = [];
    }
    groupedData[date].push(item);
  });

  // 按日期排序
  const sortedDates = Object.keys(groupedData).sort();

  // 2. 创建表格HTML
  let tableHTML = `
      <!DOCTYPE html>
      <html>
      <head>
          <meta charset="UTF-8">
          <style>
              body {
                  font-family: Arial, sans-serif;
                  margin: 0;
                  padding: 10px;
              }
              table {
                  width: 100%;
                  border-collapse: collapse;
                  table-layout: fixed;
                  text-align: center;
              }
              th, td {
                  border: 1px solid #ddd;
                  padding: 8px;
                  text-align: left;
                  word-wrap: break-word;
              }
              th {
                  background-color: #f2f2f2;
                  position: sticky;
                  top: 0;
              }
              tr:nth-child(even) {
                  background-color: #f9f9f9;
              }
              .date-cell {
                  text-align: center;
                  font-weight: bold;
                  background-color: #e6f7ff;
              }
              .merged-row {
                  background-color: #f0f0f0;
              }
          </style>
      </head>
      <body><table id="activityTable">
              <thead>
                  <tr>
                      <th>日期</th>
                      <th>时间段</th>
                      <th>地址</th>
                      <th>名称</th>
                  </tr>
              </thead>
              <tbody>
  `;

  // 3. 填充表格内容
  sortedDates.forEach((date, index) => {
    const activities = groupedData[date];
    activities.forEach((activity, index) => {
      // 添加日期行（合并单元格）
      tableHTML += `
 <tr class="merged-row">
 ${
   index == 0
     ? `<td class="date-cell" >
     <div >
      <div>${date}</div>
      <div>${activity.weekdayStr}</div>
     </div>
    </td>`
     : undefined
 }

${
  activities.length > 1 && index == 1
    ? `<td  rowspan="${activities.length - 1}">
</td>`
    : undefined
}
     <td>
     ${activity.timeAtStartStr?.split(" ")?.[1]} ~
     ${activity.timeAtEndStr?.split(" ")?.[1]}

     </td>
     <td>${activity.address || activity.impreciseAddress || "暂无"}</td>
     <td>${activity.name}</td>

 </tr>
`;
    });
  });

  tableHTML += `
              </tbody>
          </table>
      </body>
      </html>
  `;

  // 4. 将HTML转换为图片
  return await htmlToImage(tableHTML);
}

/**
 * 将HTML转换为图片
 * @param {string} html - HTML字符串
 * @returns {Promise<HTMLImageElement>}
 */
async function htmlToImage(html) {
  // 创建一个隐藏的iframe来渲染HTML
  const iframe = document.createElement("iframe");
  iframe.style.position = "fixed";
  iframe.style.top = "-99100px";
  iframe.style.left = "0px";
  iframe.style.width = "1200px"; // 设置足够宽度以避免换行
  iframe.style.height = "800px";
  document.body.appendChild(iframe);

  // 等待iframe加载
  await new Promise((resolve) => {
    iframe.contentDocument.open();
    iframe.contentDocument.write(html);
    iframe.contentDocument.close();
    iframe.onload = resolve;
  });

  // 使用html2canvas库将iframe内容转换为canvas
  const canvas = await html2canvas(
    iframe.contentDocument.querySelector("#activityTable"),
    {
      scale: 2, // 提高分辨率
      logging: false,
      useCORS: true,
      allowTaint: true,
      width: iframe.contentDocument.querySelector("#activityTable").scrollWidth,
      height:
        iframe.contentDocument.querySelector("#activityTable").scrollHeight,
    }
  );

  // 清理iframe
  document.body.removeChild(iframe);
  return duplicatingShearsClick(canvas);
  return copyCanvasWithFallback(canvas);
  // 将canvas转换为图片
  return new Promise((resolve) => {
    const img = new Image();
    img.style.position = "absolute";
    img.onload = () => resolve(img);
    img.src = canvas.toDataURL("image/png");
    document.body.appendChild(img);
  });
}
async function duplicatingShearsClick(canvas) {
  let dataURL = canvas.toDataURL({ pixelRatio: 1 });
  const data = await fetch(dataURL);
  const blob = await data.blob();
  let ClipboardItem = window.ClipboardItem;
  await navigator.clipboard.write([
    new ClipboardItem({
      [blob.type]: blob,
    }),
  ]);
  message.success("复制成功~~");
}

function copyCanvasWithFallback(canvas) {
  // 1. 生成 Data URL
  const dataUrl = canvas.toDataURL("image/png");

  // 2. 创建临时图片元素
  const img = document.createElement("img");
  img.src = dataUrl;
  img.style.maxWidth = "300px";
  img.alt = "Canvas 截图";

  // 3. 创建提示容器
  const container = document.createElement("div");
  container.style.position = "fixed";
  container.style.top = "10px";
  container.style.left = "10px";
  container.style.background = "white";
  container.style.padding = "10px";
  container.style.zIndex = "1000";
  container.appendChild(img);
  container.appendChild(document.createTextNode("按 Ctrl+C 复制图片"));

  // 4. 添加到页面并选中
  document.body.appendChild(container);

  // 5. 选中图片（部分浏览器支持直接复制选中图片）
  const range = document.createRange();
  range.selectNode(img);
  window.getSelection().removeAllRanges();
  window.getSelection().addRange(range);

  // 6. 提示用户（实际复制仍需用户手动操作）
  setTimeout(() => {
    document.body.removeChild(container);
  }, 3000);
}
export async function downloadImage(dom: HTMLElement) {
  // 使用html2canvas库将iframe内容转换为canvas
  const canvas = await html2canvas(dom, {
    scale: 2, // 提高分辨率
    logging: false,
    useCORS: true,
    allowTaint: true,
    width: dom.scrollWidth,
    height: dom.scrollHeight,
  });

  return duplicatingShearsClick(canvas);
}
